import log from '../helpers/logger';
import { CacheInterface } from 'node-easywechat';

class DbCacher extends CacheInterface {
  private db;

  constructor(db) {
    super()
    this.db = db;
    
  }

  async get(id)
  {
    log.info({ info: 'DbCacherget', id });
   // const parts = id.split('.');
   // id = parts[parts.length - 1]
   // log.info({ info: 'newid', id });
    const accessTokenRes = await this.db.app_access_token.findUnique({
      where: {
        id: id,
      },
    })
    if(accessTokenRes){
      return accessTokenRes.access_token;
    }else{
      return null;
    }  
  }

  async has(id)
  {
    log.info({ info: 'DbCacherget', id });
   // const parts = id.split('.');
   // id = parts[parts.length - 1]
   // log.info({ info: 'newid', id });
    const accessTokenRes = await this.db.app_access_token.findUnique({
      where: {
        id: id,
      },
    })
    return accessTokenRes > 0;
  }

  async set(id, data = null, lifeTime = 0)
  {
    log.info({ info: 'DbCacherget', id });
    log.info({ info: 'DbCachergetsetdata', data });
    log.info({ info: 'DbCachergetsetlifeTime', lifeTime });
    log.info({ info: 'DbCachergethas', id });
  //  const parts = id.split('.');
  //  id = parts[parts.length - 1]
  //  log.info({ info: 'newid', id });
    const nowTimestamp = Date.now();
    
    if (lifeTime > 0) {
      const date = new Date(nowTimestamp + lifeTime*1000);
      const withTimezone = date.toISOString();
      await this.db.app_access_token.upsert({
        where: {
          id: id,
        },
        update: {
          access_token: data,
          token_overtime: withTimezone

        },
        create: {
          id: id,
          access_token: data,
          token_overtime: withTimezone

        },
      });
    }
    else {
      await this.db.app_access_token.upsert({
        where: {
          id: id,
        },
        update: {
          access_token: data

        },
        create: {
          id: id,
          access_token: data
        },
      });
    }
    return true;
  }

  async delete(id)
  {
    log.info({ info: 'RedisCacherdelete', id });
 //   const parts = id.split('.');
 //   id = parts[parts.length - 1]
 //   log.info({ info: 'newid', id });
    await this.db.app_access_token.delete({
      where: {
        id: id,
      },
    });
    return true;
  }
}

export default DbCacher;

